package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**

 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    @Autowired
    private SpecGroupService specGroupService;

    @Autowired
    private SpecParamService specParamService;

    @Override
    public void addSpecGroup(SpecGroupDTO specGroupDTO) {
        SpecGroup specGroup = specGroupDTO.toEntity(SpecGroup.class);
        this.save(specGroup);
    }

    @Override
    public void updateSpecGroup(SpecGroupDTO specGroupDTO) {
        boolean update = this.updateById(specGroupDTO.toEntity(SpecGroup.class));
        if (!update) {
            throw new LyException(500, "修改失败!");
        }
    }

    @Override
    public List<SpecGroupDTO> queryGroupListByCategoryId(Long cid) {
        return SpecGroupDTO.convertEntityList(query().eq("category_id",cid).list());
    }

    @Override
    public List<SpecGroupDTO> listSpecGroup(Long id) {

        List<SpecGroupDTO> specGroupDTOS = SpecGroupDTO.convertEntityList(this.query().
                eq("category_id", id)
                .list());


        //key groupId,value,相同groupId对应的规格参数集合
        Map<Long, List<SpecParamDTO>> specParaMap = SpecParamDTO.convertEntityList(this.specParamService
                .query()
                .eq("category_id", id)
                .list())
                .stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        specGroupDTOS.forEach(specGroupDTO -> {
            specGroupDTO.setParams(specParaMap.get(specGroupDTO.getId()));
        });
        return specGroupDTOS;
    }
}
